import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

//状态管理
class ShareDataWidget extends InheritedWidget {
  const ShareDataWidget({
    Key? key,
    required this.data,
    required Widget child,
  }) : super(key: key, child: child);

  final int data; //需要在子树中共享的数据，保存点击次数

  //定义一个便捷方法，方便子树中的widget获取共享数据
  static ShareDataWidget? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>();
  }

  //该回调决定当data发生变化时，是否通知子树中依赖data的Widget重新build
  @override
  bool updateShouldNotify(ShareDataWidget old) {
    return old.data != data;
  }
}


class  _TestWidget  extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => __TestWidgetState();
}

class  __TestWidgetState extends State{

  @override
  Widget build(BuildContext context) {

       return Text(ShareDataWidget.of(context)!.data.toString());
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
      print("Dependencies change");
  }
}

class InheritedWidgetTestRoute extends StatefulWidget{

  const InheritedWidgetTestRoute({Key? key}) : super(key: key);


  @override
  State<StatefulWidget> createState() => _InheritedWidgetTestRouteState();

}

class _InheritedWidgetTestRouteState  extends State{
  int count = 0;
  @override
  Widget build(BuildContext context) {

       return  MaterialApp(
         title: "_InheritedWidgetTestRouteState",
         theme: ThemeData(primaryColor: Colors.green),
         home: Scaffold(
           appBar: AppBar(title: const Text("InheritedWidgetTestRouteState"),),
           body: Center(
             child: ShareDataWidget( //使用ShareDataWidget
               data: count,
               child: Column(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: <Widget>[
                   Padding(
                     padding: const EdgeInsets.only(bottom: 20.0),
                     child: _TestWidget(),//子widget中依赖ShareDataWidget
                   ),
                   ElevatedButton(
                     child: const Text("Increment"),
                     //每点击一次，将count自增，然后重新build,ShareDataWidget的data将被更新
                     onPressed: () => setState(() => ++count),
                   )
                 ],
               ),
             ),
           ),
         ),
       );
       }
  }


